<?php


namespace App\Services;


use GuzzleHttp\Client;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class WechatApi
{
    protected static $app_id = '';

    protected static $app_secret = '';

    public static function getUser($code)
    {
        $data = json_decode(file_get_contents('https://api.weixin.qq.com/sns/jscode2session?'.http_build_query([
                'appid'     => self::$app_id,
                'secret'    => self::$app_secret,
                'js_code'   => $code,
                'grant_type'=> 'authorization_code',
            ])),true);

        if (isset($data['errcode'])){

            Log::error('微信登录失败',$data);
            return false;
        }

        return $data;

    }

    public static function getAccessToken()
    {
        $result = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?'.http_build_query([
            'grant_type'=> 'client_credential',
            'appid'     => self::$app_id,
            'secret'    => self::$app_secret,
            ]));

        $data = json_decode($result);

        if (isset($data->errcode)){

            throw new \Exception($data->errmsg,$data->errcode);
        }

        return $data->access_token;
    }


    public static function createQRCode(string $page,array $scene, int $width = 430)
    {
        $http = new Client();

        $result = Http::post('https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.self::getAccessToken(),[
            'scene'         => http_build_query($scene),
            'width'         => $width
        ]);

        $data = json_decode($result);

        if (isset($data->errcode)){

            throw new \Exception($data->errmsg,$data->errcode);
        }

        $file_name = 'public/mini/'.md5(json_encode($scene)).'.jpg';

        Storage::put($file_name,$result);

        return Storage::url($file_name);
    }
}
